package com.chookss.home.audit.overtime;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.ApprovalProcessActivity;
import com.chookss.home.audit.adapter.FilesHolidyAdapter;
import com.chookss.home.audit.clockIn.ClockInAskHolidayActivity;
import com.chookss.home.audit.clockIn.ClockInUtils;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.HolidayDetailEntity;
import com.chookss.home.entity.ProcessEntity;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OvertimeDetailActivity extends BaseAct {
    //加班详情页
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.tvGroup)
    TextView tvGroup;
    @BindView(R.id.tvStartTime)
    TextView tvStartTime;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.tvTimeLength)
    TextView tvTimeLength;
    @BindView(R.id.llGroup)
    LinearLayout llGroup;
    @BindView(R.id.groupEmpty)
    View groupEmpty;
    @BindView(R.id.edContent)
    TextView edContent;
    @BindView(R.id.fileRcv)
    RecyclerView fileRcv;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.tvCancel)
    TextView tvCancel;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.common_right_txt)
    TextView common_right_txt;
    @BindView(R.id.llProcess)
    LinearLayout llProcess;
    @BindView(R.id.llProcessTop)
    LinearLayout llProcessTop;
    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.tvProcessTitle)
    TextView tvProcessTitle;
    @BindView(R.id.tvProcessTitleInit)
    TextView tvProcessTitleInit;
    @BindView(R.id.tvProcessStatus)
    TextView tvProcessStatus;
    @BindView(R.id.emptyProcess)
    View emptyProcess;
    @BindView(R.id.emptyBottom)
    View emptyBottom;
    private static final int REQUEST_CODE_CHOOSE = 23;
    private WorkNewEntity workNewEntity = null;
    private List<ProcessEntity> list = new ArrayList<>();
    private ProcessEntity endProcessEntity = null;
    private String workflowId = "", qingjiaWorkflowCode = "";
    private String tag = "ClockInAskHolidayDetailActivity_DownloadFile";//下载文件打的标签
    private String projectCode="",employeeCode="",title="";
    private List<HolidayDetailEntity.AnnexsBean> filesList = new ArrayList<>();
    private FilesHolidyAdapter adapter;
    private int type=4;//类型

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_in_ask_holiday_detail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        common_right_txt.setText("审批流程");
        common_right_txt.setVisibility(View.VISIBLE);
        workNewEntity = (WorkNewEntity) getIntent().getSerializableExtra("data");
        projectCode=getIntent().getStringExtra("projectCode");
        employeeCode=getIntent().getStringExtra("employeeCode");
        title=getIntent().getStringExtra("title");
        fileRcv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new FilesHolidyAdapter(R.layout.item_files_list, this, filesList, 1, tag);
        fileRcv.setAdapter(adapter);
        if (workNewEntity != null) {
            commonTitleTxt.setText(workNewEntity.getProjectName());
        } else {
            commonTitleTxt.setText(title);
        }
        selectKaoqinDeail();
        registerBoradcastReceiver();
    }

    private void selectKaoqinDeail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        if(Utils.isNull(projectCode)){
            if(workNewEntity!=null) {
                map.put("projectCode", workNewEntity.getProjectCode());
            }
        }else{
            map.put("projectCode", projectCode);
        }
        map.put("type", "4");//3补卡 4请假
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<HolidayDetailEntity>>() {
        }.getType(), null, Urls.selectKaoqinDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<HolidayDetailEntity>() {
            @Override
            public void onSuccess(HolidayDetailEntity data) {
                if (data != null) {
                    if(tvTimeLength==null){
                        return;
                    }
                    workflowId = data.getWorkflowId();
                    qingjiaWorkflowCode = data.getQingjiaWorkflowCode();
                    if (!Utils.isNull(data.getGroupCode())) {
                        tvGroup.setText(data.getItemGroupName() + "(" + ClockInUtils.getGroupEnd(data.getGroupCode()) + ")");
                        groupEmpty.setVisibility(View.VISIBLE);
                        llGroup.setVisibility(View.VISIBLE);
                    }

                    tvTimeLength.setText(data.getQingjiaLength() + "天");
                    tvStartTime.setText(data.getStartTime());
                    tvEndTime.setText(data.getEndTime());
                    tvType.setText(data.getBaoixaoTypeName());
                    filesList.addAll(data.getAnnexs());
                    for (int i = 0; i < filesList.size(); i++) {
                        if ((filesList.get(i).getDatabase().size() + filesList.get(i).getPictureInfoList().size()) == 0) {
                            filesList.remove(i);
                            if (i < filesList.size()) {
                                i--;
                            }
                        }
                    }
                    adapter.notifyDataSetChanged();
                    if (Utils.isNull(data.getRemark())) {
                        edContent.setText("无");
                    } else {
                        edContent.setText(data.getRemark());
                    }
//                    if ("1".equals(data.getAuditCd()) || "3".equals(data.getAuditCd())) {
//                        //0待审核1审核通过2未通过3废弃
//                        llBottom.setVisibility(View.GONE);
//                    } else {
                        //0么有权限1展示通过不通过2展示废弃修改
                        if (Utils.isNull(data.getAuditFlag())) {
                            llBottom.setVisibility(View.GONE);
                            getProcessData();
                        } else {
                            if ("1".equals(data.getAuditFlag()) || "2".equals(data.getAuditFlag())) {
                                llBottom.setVisibility(View.VISIBLE);
                                if ("2".endsWith(data.getAuditFlag())) {
                                    tvSure.setText("修改");
                                    tvCancel.setText("废弃");
                                }
                            } else {
                                llBottom.setVisibility(View.GONE);
                                getProcessData();
                            }
                        }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void getProcessData() {
        //审批进度
        Map<String, String> map = new HashMap<>();
        if(Utils.isNull(projectCode)){
            if(workNewEntity!=null) {
                map.put("projectCode", workNewEntity.getProjectCode());
            }
        }else{
            map.put("projectCode", projectCode);
        }
        map.put("type", type+"");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ProcessEntity>>>() {
        }.getType(), null, Urls.selectAuditDetailList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ProcessEntity>>() {
            @Override
            public void onSuccess(List<ProcessEntity> data) {
                String name = "", headUrl = "";
                List<ProcessEntity> processEntityList = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    processEntityList.add(data.get(i));
                    if (data.get(i).getConnectType().equals("0")) {
                        name = data.get(i).getCreateEmployeeName();
                        headUrl = data.get(i).getHeadPhotoThumbUrl();
                    }
                    if (data.get(i).getEndStep().equals("1")) {
                        ProcessEntity endProcessEntity = new ProcessEntity();
                        if (Utils.isNull(name)) {
                            endProcessEntity.setCreateEmployeeName(data.get(0).getCreateEmployeeName());
                            endProcessEntity.setRealAuditEmployeeName(data.get(0).getCreateEmployeeName());
                        } else {
                            endProcessEntity.setCreateEmployeeName(name);
                            endProcessEntity.setRealAuditEmployeeName(name);
                        }
                        if (Utils.isNull(headUrl)) {
                            endProcessEntity.setHeadPhotoThumbUrl(data.get(0).getHeadPhotoThumbUrl());
                        } else {
                            endProcessEntity.setHeadPhotoThumbUrl(headUrl);
                        }
                        endProcessEntity.setConnectType("0");
                        endProcessEntity.setEndProcess(true);
                        endProcessEntity.setAuditStatus("1");
                        processEntityList.add(endProcessEntity);
                    }
                }
                if (data.size() > 0) {
                    llProcess.setVisibility(View.VISIBLE);
                    emptyProcess.setVisibility(View.VISIBLE);
                    emptyBottom.setVisibility(View.GONE);
                    setProcessDetail(processEntityList.get(processEntityList.size() - 1));
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void setProcessDetail(ProcessEntity entity) {
        if (!Utils.isNull(entity.getHeadPhotoThumbUrl())) {
            GlideUtils.loadAvatar(this, entity.getHeadPhotoThumbUrl(), ivHead);
        } else {
            GlideUtils.loadAvatar(this, new ShareUtils().getString(this, StaticClass.ORIGINALURL, ""), ivHead);
        }
        if (entity.isEndProcess()) {
            //已结束
            llProcessTop.setVisibility(View.GONE);
            tvProcessStatus.setText("已结束");
            tvProcessStatus.setTextColor(Color.parseColor("#00C993"));
        } else {
            //getWorkFlowName  环节名称
            //getAuditEmployeeName  项目组
            //getRealAuditEmployeeName   真实审批人
            // connectType //0发起人1行政审批  只有0和1不展示（）中的项目名称，其余的需要展示
            //格式 环节名称（项目名称）
            if ("0".equals(entity.getConnectType()) || "1".equals(entity.getConnectType())) {
                tvProcessTitle.setText(entity.getWorkFlowName());
            } else {
                if (Utils.isNull(entity.getWorkFlowName())) {
                    tvProcessTitle.setText(entity.getWorkFlowName());
                    tvProcessTitleInit.setText(entity.getAuditEmployeeName());
                } else {
                    if (Utils.isNull(entity.getAuditEmployeeName())) {
                        tvProcessTitle.setText(entity.getWorkFlowName());
                        tvProcessTitleInit.setText("");
                    } else {
                        tvProcessTitle.setText(entity.getWorkFlowName());
                        tvProcessTitleInit.setText("(" + entity.getAuditEmployeeName() + ")");
                    }
                }
            }
            //1审核通过 2审核未通过0未审核3废弃
            if ("0".equals(entity.getAuditStatus())) {
                if ("0".equals(entity.getConnectType())) {
                    tvProcessStatus.setText("待修改");
                } else {
                    if (Utils.isNull(entity.getAuditEmployeeName())) {
                        tvProcessStatus.setText("待审批");
                    } else {
                        tvProcessTitleInit.setText("");
                        tvProcessStatus.setText("待" + entity.getAuditEmployeeName() + "审批");
                    }

                }
                tvProcessStatus.setTextColor(Color.parseColor("#FCA817"));
            } else if ("1".equals(entity.getAuditStatus())) {
                if ("0".equals(entity.getConnectType())) {
                    if (type == 8) {
                        if ("5".equals(entity.getParams().getStatusCd())) {
                            tvProcessStatus.setText("发起物品遗失申请");
                        } else if ("6".equals(entity.getParams().getStatusCd())) {
                            tvProcessStatus.setText("发起物品报废申请");
                        } else {
                            tvProcessStatus.setText("重新提交");
                        }
                    } else if (type == 9) {
                        if ("1".equals(entity.getParams().getRepaymentCd())) {
                            tvProcessStatus.setText("发起还款申请");
                        } else {
                            tvProcessStatus.setText("重新提交");
                        }
                    } else {
                        tvProcessStatus.setText("重新提交");
                    }
                } else {
                    if ("1".equals(entity.getReplaceCd())) {
                        //超管待审
                        tvProcessStatus.setText("超管代审批通过");
                    } else {
                        tvProcessStatus.setText("审批通过");
                    }

                }
                tvProcessStatus.setTextColor(Color.parseColor("#00C993"));
            } else {
                if ("3".equals(entity.getAuditStatus())) {
                    tvProcessStatus.setText("废弃");
                } else {
                    if ("1".equals(entity.getReplaceCd())) {
                        //超管待审
                        tvProcessStatus.setText("超管代审批不通过");
                    } else {
                        tvProcessStatus.setText("审批不通过");
                    }
                }
                tvProcessStatus.setTextColor(getResources().getColor(R.color.main_color));
            }
        }
    }

    private void passData(int auditStatus) {
        Map<String, Object> map = new HashMap<>();
        //1审核通过 2审核未通过0未审核
        Map<String, String> news = new HashMap<>();
        List<Map<String, String>> lists = new ArrayList<>();
        news.put("id", workflowId);
        news.put("projectCode", qingjiaWorkflowCode);
//        ////0新闻2图文3补卡4请假
        news.put("type", "4");
        news.put("auditStatus", auditStatus + "");
        if(Utils.isNull(projectCode)){
            if(workNewEntity!=null){
                news.put("employeeCode", workNewEntity.getCreateEmployeeCode());
            }
        }else{
            news.put("employeeCode",employeeCode);
        }

        lists.add(news);
        map.put("tbKmerWorkFlowProjects", XJson.listToJsArrays(lists));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.auditWorkfolwProject, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }

    private void deleteData() {
        Map<String, String> map = new HashMap<>();
        map.put("workflowId", workflowId);
        map.put("qingjiaWorkflowCode", qingjiaWorkflowCode);
        map.put("workflowType", "4");
        showLoading();
        MyHttpRequest.postRequest(Urls.deleteQingjiaInfo, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }

    @OnClick({R.id.common_title_back, R.id.llProcess, R.id.tvCancel, R.id.common_right_txt,R.id.tvSure})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
            case R.id.llProcess:
                if (Urls.antiShake.check()) {
                    return;
                }
                intent = new Intent(this, ApprovalProcessActivity.class);
                intent.putExtra("projectCode", workNewEntity.getProjectCode());
                intent.putExtra("type", 4);
                startActivity(intent);
                break;
            case R.id.tvCancel:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (tvCancel.getText().toString().equals("不通过")) {
                    passData(2);
                } else {
                    deleteData();
                }
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (tvSure.getText().toString().equals("通过")) {
                    passData(1);
                } else {
                    intent = new Intent(this, ClockInAskHolidayActivity.class);
                    intent.putExtra("qingjiaWorkflowCode", qingjiaWorkflowCode);
                    intent.putExtra("workflowId", workflowId);
                    startActivity(intent);
                    finish();
                }
                break;
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                if (encryptStatus) {
                    for (int i = 0; i < filesList.size(); i++) {
                        for (int j = 0; j < filesList.get(i).getDatabase().size(); j++) {
                            if (filesList.get(i).getDatabase().get(j).getDataCode().equals(recevierDataCode)) {
                                if (!filesList.get(i).getDatabase().get(j).isOpen()) {
                                    if (encryptStatus) {
                                        filesList.get(i).getDatabase().get(j).setOpen(true);
                                    }
                                    dealData(0, 0, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                                }

                            }
                        }
                    }
                } else {
                    int parent = 0;
                    int child = 0;
                    String datas = position + "";
                    if (datas.length() > 1) {
                        parent = Utils.changeNumber(datas.substring(0, 1));
                        child = Utils.changeNumber(datas.substring(1, 2));
                    }
                    for (int i = 0; i < filesList.get(parent).getDatabase().size(); i++) {
                        if (filesList.get(parent).getDatabase().get(i).getDataCode().equals(recevierDataCode)) {
                            if (!filesList.get(parent).getDatabase().get(i).isOpen()) {
                                if (encryptStatus) {
                                    filesList.get(parent).getDatabase().get(i).setOpen(true);
                                }
                                dealData(parent, child, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                            }

                        }
                    }
                }

            }
        }

    };

    /**
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int parent, int child, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        } else {
            if (percent > 0 && percent < 100) {
                if (adapter != null) {
                    filesList.get(parent).getDatabase().get(child).setProgress(percent);
                    adapter.setRefresh(child);
                }
            } else if (percent == 100) {
                if (adapter != null) {
                    filesList.get(parent).getDatabase().get(child).setProgress(100);
                    adapter.setRefresh(child);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(OvertimeDetailActivity.this, fileUrl, fileName, recevierDataCode, tag);
                        }
                    }.start();
                }


            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(tag);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
    }
}
